package com.rongke.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.alipayUtil.PayUtils;
import com.rongke.alipayUtil.alipay.util.httpClient.HttpRequest;
import com.rongke.commons.FailException;
import com.rongke.commons.JsonResp;
import com.rongke.enums.OrderStatusEnum;
import com.rongke.enums.PayTypeEnum;
import com.rongke.enums.UserTypeEnum;
import com.rongke.model.*;
import com.rongke.redis.CacheUtil;
import com.rongke.service.*;
import com.rongke.utils.HttpClientUtil;
import com.rongke.utils.OrderUtils;
import com.rongke.utils.RequestUtils;
import com.rongke.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @version : Ver 1.0
 * @OrdersController
 * @订单Controller
 */
@RestController
@RequestMapping(value = "/api/orders")
@Transactional
@CrossOrigin
public class OrdersController {
    private Logger log = Logger.getLogger(this.getClass());
    //第一梯队，江浙沪包邮时
    private List<String> firstProvinces = Arrays.asList("浙江", "江苏", "上海");
    //第二梯队列表，除
    private List<String> secProvinces = Arrays.asList("北京",  "天津", "江西", "安徽", "广东",  "福建", "山东",  "河北",  "河南", "湖南");

    //第三梯队
//    四川、重庆、贵州、云南、广西、山西、陕西、海南、辽宁、黑龙江、吉林
    private List<String> thirdProvinces=Arrays.asList("四川","重庆","贵州","云南","广西","山西","陕西","海南","辽宁","黑龙江","吉林");

    //第四梯队，全国包邮时不包括的省
    private List<String> fourthProvinces = Arrays.asList("香港", "澳门"
            , "台湾", "西藏自治区", "西藏", "新疆维吾尔自治区", "新疆", "内蒙古自治区", "内蒙古", "宁夏回族自治区", "宁夏", "青海省", "青海", "甘肃省", "甘肃");


    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private CouponUserService couponUserService;
    @Autowired
    private BuyTogetherGoodsService buyTogetherGoodsService;
    @Autowired
    private BuyTogetherUserService buyTogetherUserService;
    @Autowired
    private MuserService muserService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private ShoppingCarService shoppingCarService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private FlowDetailService flowDetailService;
    @Autowired
    private ExperienceGoodsService experienceGoodsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private DeliveryItemService deliveryItemService;

    public static String alinotify = "/api/money/alipay/orderSucc";
    public static String wxnotify = "/api/money/wxpay/orderSucc";

    public OrdersController() {
    }

    /**
     * @param orders
     * @return 返回值JsonResp
     * @添加订单
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addOrders(@RequestBody Orders orders, Integer shopCarStatus) {
        log.debug("添加订单");
        HttpServletRequest request = RequestUtils.getRequest();
        Integer versionCode=request.getIntHeader("versionCode");//用getIntHeader方法返回字符串值转换的int值，不存在返回-1
        if(null==versionCode||-1==versionCode||versionCode<21){
            return JsonResp.toFail("因版本太旧，请更新APP后再购买。");
        }
        if (null == orders.getOrderType() || null == orders.getMuserId()) {
            return JsonResp.toFail("订单类型参数和用户id不能为空");
        } else if (orders.getOrderType() == 2) {
            //如果是试用众测订单查看当前是否有收货**天未填问卷的
            if (experienceGoodsService.ifLeftOversExpOrdersExist(orders.getMuserId())) {
                return JsonResp.toFail("你尚有已收货的体验订单未在规定时间内填写问卷，暂时不能下单");
            }
        }
        Address address = addressService.selectById(orders.getAddressId());
        orders.setReceiverAddress(address.getProvince() + address.getCity() + address.getArea() + address.getAddressDetail());
        orders.setReceiverName(address.getName());
        orders.setReceiverPhone(address.getPhone());
        orders.setGmtDatetime(new Date());
        String orderNumber = OrderUtils.getOrderNo();
        orders.setOrderNumber(orderNumber);
        orders.setOrderStatus(OrderStatusEnum.WAIT_PAY.getType());
        ordersService.insert(orders);
        //使用优惠券时更改优惠券状态为 3 已使用
        if (orders.getUseCoupon() != null) {
            CouponUser cu = couponUserService.selectById(orders.getUseCoupon());
            if (cu != null) {
                cu.setStatus(3);
                couponUserService.updateById(cu);
            }
        }
        List<OrderGoods> orderGoodsList = orders.getOrderGoodsList();
        for (OrderGoods og : orderGoodsList) {
            og.setOrderId(orders.getId());
            og.setGmtDatetime(new Date());
        }
        orderGoodsService.insertBatch(orderGoodsList);
        if (shopCarStatus == 1) {  //如果从购物车中提交的订单需要清空购物车
            //清空购物车
            shoppingCarService.emptyShoppingCart(orders.getId());
        }
        Muser muser = muserService.selectById(orders.getMuserId());
        Map map = new HashMap();
        map.put("orders", orders);
        map.put("nums", muser.getNums());
        return JsonResp.ok(map);
    }

    /**
     * @param orders
     * @return 返回值JsonResp
     * @修改订单
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateOrders(@RequestBody Orders orders) {
        log.debug("修改订单");
        orders.setUptDatetime(new Date());
        ordersService.updateById(orders);
        return JsonResp.ok(orders);
    }

    /**
     * 取消订单
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "/cancelOrder", method = RequestMethod.POST)
    public JsonResp cancelOrder(@RequestBody Orders order) {
        log.debug("用户取消订单");
        if (order.getId() == null)
            return JsonResp.toFail("订单id为空");
        log.debug("订单id为" + order.getId());
        EntityWrapper<Orders> ew = new EntityWrapper<>(order);
        Orders od = ordersService.selectOne(ew);
        //更改订单状态为 7 买家取消
        od.setOrderStatus(7);
        ordersService.updateById(od);
        Long couponId = od.getUseCoupon();
        if (couponId != null) {
            CouponUser cu = couponUserService.selectById(couponId);
            if (cu != null) {
                //重新设置
                cu.setStatus(1);
                couponUserService.updateById(cu);
            }
        }
        return JsonResp.ok("取消订单成功", od);
    }

    /**
     * 批量更新订单（发货等）
     *
     * @param ordersList
     * @return
     */
    @RequestMapping(value = "/uptOrderBatch", method = RequestMethod.POST)
    public JsonResp uptOrderBatch(@RequestBody List<Orders> ordersList) {
        log.debug("批量更新订单（发货等）");
        ordersService.updateBatchById(ordersList);
        return JsonResp.ok(ordersList);
    }


    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找订单
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectOrders(Long id) {
        log.debug("查找订单");
        Orders orders = ordersService.selectById(id);
        return JsonResp.ok(orders);
    }

    /**
     * @param orders
     * @return 返回值JsonResp
     * @根据条件查找订单
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectOrdersByCondition(@RequestBody Orders orders) {
        log.debug("根据条件查找订单");
        if (orders == null)
            return JsonResp.toFail("参数不能为空");
        List<Orders> ordersList = ordersService.selectByCondition(orders);
        return JsonResp.ok(ordersList);
    }


    /**
     * @param token       安全令牌
     * @param orderNumber 订单编号
     * @param payWay      支付方式
     * @return 返回值JsonResp
     * @支付订单
     */
    @RequestMapping(value = "/payOrder", method = RequestMethod.POST)
    public JsonResp payOrder(String token, String orderNumber, Integer payWay, HttpServletRequest request) {
        log.debug("支付订单");
        EntityWrapper<Orders> ew = new EntityWrapper<>();
        ew.eq("order_number", orderNumber);
        Orders orders = ordersService.selectOne(ew);
        Long orderId = orders.getId();
        if (orders == null) {
            return JsonResp.fa("订单不存在");
        }
        if (orders.getOrderStatus() != OrderStatusEnum.WAIT_PAY.getType()) {
            return JsonResp.fa("该订单已支付");
        }

        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        EntityWrapper<Account> ewAcc = new EntityWrapper<>();
        ewAcc.eq("muser_id", orders.getMuserId());
        Account account = accountService.selectOne(ewAcc);
        BigDecimal money = null;
        if (orders.getAllowPayType() == 1) {
//            if (account.getDuoBi().compareTo(orders.getTotalPrice()) < 0) {
//                money = orders.getTotalPrice().subtract(account.getDuoBi());
//            } else {
//                money = orders.getTotalPrice();
//            }
            money = orders.getTotalPrice();
        } else if (orders.getAllowPayType() == 2) {
            if (account.getYaBi().compareTo(orders.getTotalPrice()) < 0) {
                money = orders.getTotalPrice().subtract(account.getYaBi());
            } else {
                money = orders.getTotalPrice();
            }
        }
        Long userId = Long.valueOf(cacheUtil.get(token));
        Lock lock = new ReentrantLock();
        try {
            lock.lock();
            //减库存
            JSONObject jsonInven = ordersService.updateInventory(orderId);
            if ("500".equals(jsonInven.getString("code"))) {
                return JsonResp.fa("抢光啦");//库存不足
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        //如果是拼团订单
        if (orders.getOrderType() == 1) {
            //拼团插入数据
            String buyTogetherCode = orders.getBuyTogetherCode();//开团号
            JSONObject jsonObject1 = buyTogetherUserService.insertButogetherUserData(orderId, buyTogetherCode);
            if ("500".equals(jsonObject1.get("code"))) {
                return JsonResp.fa(jsonObject1.getString("message"));
            }
        }

        if (payWay == PayTypeEnum.ZHIFUBAO.getType()) {
            String sym = request.getRequestURL().toString().split("/api/")[0].replace("http", "https");
            String trade_no = null;
            trade_no = (orderId + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0, 32);
            String stringStringMap = null;
            try {
                stringStringMap = PayUtils.AliPay(trade_no, money.doubleValue(), "支付宝支付", "支付宝支付—", sym + alinotify);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (StringUtil.isNotEmpty(stringStringMap)) {
                return JsonResp.ok("成功", stringStringMap);
            } else {
                log.debug("支付宝支付失败");
                throw new FailException();
            }

        } else if (payWay == PayTypeEnum.WEIXIN.getType()) {
            String sym = request.getRequestURL().toString().split("/api/")[0].replace("http", "https");
            String trade_no = null;
            trade_no = (orderId + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0, 32);
            Map map;
            map = PayUtils.WxPay(trade_no, money.doubleValue(), "微信支付", sym + wxnotify);
            if (!map.isEmpty()) {
                return JsonResp.ok("成功", map);
            } else {
                log.debug("微信支付失败");
                throw new FailException();
            }

        } else {
            //余额支付
            JSONObject jsonObject = ordersService.OrdersPay(orderId, payWay);
            if ("500".equals(jsonObject.getString("code"))) {
                return JsonResp.fa("支付失败");
            }
            //更新订单状态
            orders.setPayType(payWay);
            if (orders.getOrderType() == 1) {
                orders.setOrderStatus(OrderStatusEnum.BUYTOGETHER.getType());
            } else {
                orders.setOrderStatus(OrderStatusEnum.WAIT_SHIP.getType());
            }
            orders.setPayDatetime(new Date());
            ordersService.updateById(orders);
            // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为百夫长，则第一个百夫长不可用余额增加
            Muser recomendMuser = muserService.findFirstRecomendUser(userId, UserTypeEnum.CENTURION.getType());
            if (recomendMuser != null) {
                JSONObject jsonRecomend = accountService.updateRecomendUserAccount(recomendMuser.getId(), orderId);
                if ("500".equals(jsonRecomend.getString("code"))) {
                    return JsonResp.fa(jsonRecomend.getString("message"));
                }
            }
            // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为千夫长，则第一个千夫长不可用余额增加
            Muser chiefCommander = muserService.findFirstRecomendUser(userId, UserTypeEnum.ChIEFCOMMANDER.getType());
            if (chiefCommander != null) {
                JSONObject jsonChief = accountService.updateRecomendUserAccount(chiefCommander.getId(), orderId);
                if ("500".equals(jsonChief.getString("code"))) {
                    return JsonResp.fa(jsonChief.getString("message"));
                }
            }
            // 获取购买人推荐人关系链，如果关系链上面有一个或多个推荐人为加盟商，则第一个加盟商不可用余额增加
            Muser franchisee = muserService.findFirstRecomendUser(userId, UserTypeEnum.FRANCHISEE.getType());
            if (franchisee != null) {
                JSONObject jsonChief = accountService.updateRecomendUserAccount(franchisee.getId(), orderId);
                if ("500".equals(jsonChief.getString("code"))) {
                    return JsonResp.fa(jsonChief.getString("message"));
                }
            }
        }

        return JsonResp.ok(orders);
    }


    /**
     * 根据订单id获取返回的哆币和雅币
     *
     * @param orderId 订单id
     * @return 返回值JsonResp
     * @立即购买
     */
    @RequestMapping(value = "/findReturnDuobiAndYaBi", method = RequestMethod.GET)
    public JsonResp findReturnDuobiAndYaBi(Long orderId) {
        log.debug("根据订单id获取返回的哆币和雅币");
        Orders orders = ordersService.selectById(orderId);
        JSONObject jsonObject = orderGoodsService.findCashBackYbAndDuoBi(orderId, orders.getMuserId());
        Map map = new HashMap();
        if ("200".equals(jsonObject.get("code"))) {
            map.put("totalReurnRate", jsonObject.get("totalReurnRate"));
            map.put("totalReturnRatey", jsonObject.get("totalReturnRatey"));
        }

        return JsonResp.ok(map);

    }


    /**
     * @param token       令牌
     * @param orderNumber 订单id
     * @return
     * @确认收货
     */
    @RequestMapping(value = "/confirmReceiptOrder", method = RequestMethod.GET)
    public JsonResp confirmReceiptOrder(String token, String orderNumber) {
        log.debug("确认收货");
        if (!cacheUtil.hasKey(token)) {
            return JsonResp.fa(muserService.LOGINSTR);
        }
        Long userId = Long.valueOf(cacheUtil.get(token));
        EntityWrapper<Orders> ew = new EntityWrapper<>();
        ew.eq("order_number", orderNumber);
        Orders orders = ordersService.selectOne(ew);
        Long orderId = orders.getId();
        //更新订单状态
        orders.setOrderStatus(OrderStatusEnum.PENDING_EVALUATION.getType());
        orders.setUptDatetime(new Date());
        orders.setCompleteDatetime(new Date());
        ordersService.updateById(orders);
        //确认收货后返现操作
        JSONObject jsonObject = ordersService.confirmReceiptOrder(userId, orderId);
        if ("500".equals(jsonObject.getString("code"))) {
            return JsonResp.fa(jsonObject.getString("message"));
        }

        return JsonResp.ok();

    }

    /**
     * 用户端删除订单
     *
     * @param orderNumber
     * @return
     */
    @RequestMapping(value = "/delOrderByUesr", method = RequestMethod.GET)
    public JsonResp delOrderByUesr(String orderNumber) {
        log.debug("用户端删除订单:订单编号为" + orderNumber);
        if (StringUtil.isEmpty(orderNumber))
            return JsonResp.toFail("订单编号不能为空");
        EntityWrapper<Orders> ew = new EntityWrapper<>();
        ew.eq("order_number", orderNumber);
        Orders order = ordersService.selectOne(ew);
        if (null == order)
            return JsonResp.toFail("未查到相关订单");
        Orders newOrder = new Orders();
        newOrder.setId(order.getId());
        newOrder.setIsDelete(0);
        ordersService.updateById(newOrder);
        return JsonResp.ok(newOrder);
    }

    /**
     * @param orderPage
     * @return
     * @分页条件获取所有订单列表
     */
    @RequestMapping(value = "/getAllOrdersByCondition", method = RequestMethod.POST)
    public JsonResp getAllOrdersByCondition(@RequestBody Page<Orders> orderPage) {
        log.debug("分页条件获取所有订单列表");
        /*15分钟未付款自动取消订单*/
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MINUTE, -15);
        EntityWrapper<Orders> ew = new EntityWrapper<>();
        ew.eq("order_status", 1);
        ew.lt("gmt_datetime", cal.getTime());
        List<Orders> orders = ordersService.selectList(ew);
        if (orders.size() > 0) {
            orders.forEach(e -> {
                //6自动取消
                e.setOrderStatus(6);
            });
            ordersService.updateBatchById(orders);
        }
        Map condition = orderPage.getCondition();
//        Integer orderStatus = (Integer) condition.get("orderStatus");
        //当状态参数为99时表示查询已完成和待评价相加订单
       /* if (null != orderStatus && orderStatus == 99) {
            orders.setOrderStatus(null);
        }*/
//        分页查询 带Page时由mybatis-plus自动分页，无需在mapper中写分页查
        Integer startIndex = (orderPage.getCurrent() - 1) * orderPage.getSize();
        Integer size = orderPage.getSize();
        condition.put("startIndex", startIndex);
        condition.put("size", size);
        List<Orders> orderRecords = ordersService.selectOrderListWithCondition(condition);
        orderPage.setRecords(orderRecords);
        Integer total = ordersService.selectOrderListSize(condition);
        orderPage.setTotal(total);
        //当状态参数为99时表示查询已完成和待评价相加订单 4 已完成 5 待评价
        return JsonResp.ok(orderPage);
    }

    /**
     * 根据用户id获取不同状态的订单列表
     *
     * @param orderPage
     * @return
     */
    @RequestMapping(value = "/getDiffStatusOrdersByMuserId", method = RequestMethod.POST)
    public JsonResp getDiffStatusOrdersByMuserId(@RequestBody OrderPage orderPage) {
        log.debug("根据用户id获取不同状态的订单列表");
        Orders orders = orderPage.getOrders();
        if (null == orders.getMuserId())
            return JsonResp.toFail("用户id参数不能为空");
        EntityWrapper<Orders> ew = new EntityWrapper<>();
        ew.eq("muser_id", orders.getMuserId());
        if (orders.getSourceType() != null) {
            ew.eq("source_type", orders.getSourceType());
        }
        //用户端是否删除订单 0 已删除 1 未删除
        ew.eq("is_delete", 1);
        ew.orderBy("gmt_datetime", false);
        if (null != orders.getOrderStatus()) {
                 /*15分钟未付款自动取消订单*/
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(Calendar.MINUTE, -15);
            EntityWrapper<Orders> ew1 = new EntityWrapper<>();
            ew1.eq("order_status", 1);
            ew1.lt("gmt_datetime", cal.getTime());
            ew1.eq("muser_id", orders.getMuserId());
            List<Orders> orderList = ordersService.selectList(ew1);
            if (orderList.size() > 0) {
                orderList.forEach(e -> {
                    //6自动取消
                    e.setOrderStatus(6);
                });
                ordersService.updateBatchById(orderList);
            }
            ew.eq("order_status", orders.getOrderStatus());
        } else {
            //排除掉拼团待成团的订单
            String orderStatus = "";
            for (OrderStatusEnum userTypeEnum : OrderStatusEnum.values()) {
                if (userTypeEnum.getType() != OrderStatusEnum.BUYTOGETHER.getType()) {
                    orderStatus += userTypeEnum.getType() + ",";
                }
            }
            if (!"".equals(orderStatus)) {
                orderStatus = orderStatus.substring(0, orderStatus.length() - 1);
            }
            ew.where("find_in_set(orders.order_status,{0}) >0", orderStatus);
        }
        //获取某订单类型，我的体验（试用众测）订单等
        if (null != orders.getOrderType()) {
            ew.eq("order_type", orders.getOrderType());
        }
        Page<Orders> page = ordersService.selectPage(orderPage.getPage(), ew);
        if (page.getSize() == 0)
            return JsonResp.ok(page);
        List<Orders> orders1 = page.getRecords();
        //查询订单下商品、地址、发起人详情
        for (Orders item : orders1) {
            Long oId = item.getId();
            if (null != oId) {
                List<OrderGoods> ogList = orderGoodsService.selectOrderGoodsByOrderId(oId);
                item.setOrderGoodsList(ogList);
            }
        }
        page.setRecords(orders1);
        return JsonResp.ok(page);
    }

    /**
     * 根据订单编号查询订单详情
     *
     * @param orderNumber
     * @return
     */
    @RequestMapping(value = "/getOrderDetailByOrderId", method = RequestMethod.GET)
    public JsonResp getOrderDetailByOrderId(String orderNumber) {
        log.debug("根据订单编号查询订单详情");
        if (StringUtil.isEmpty(orderNumber))
            return JsonResp.toFail("server:订单编号不能为空");
        EntityWrapper<Orders> ew = new EntityWrapper<>();
        ew.eq("order_number", orderNumber);
        Orders orders = ordersService.selectOne(ew);
        orders.setLogiCom(ShippingEnum.getLogiComNameByCode(orders.getLogiCom()));
        List<OrderGoods> ogList = orderGoodsService.selectOrderGoodsByOrderId(orders.getId());
        orders.setOrderGoodsList(ogList);
/*        Long addressId = orders.getAddressId();
        //获取收货地址、收货人等信息
        if (null != addressId) {
            Address tempAddress = addressService.selectById(addressId);
            orders.setAddress(tempAddress);
        }*/
        //获取买家信息
        Long muserId = orders.getMuserId();
        if (null != muserId) {
            Muser tempMuser = muserService.selectById(muserId);
            orders.setMuser(tempMuser);
        }
        return JsonResp.ok(orders);
    }

    /**
     * 获取订单物流详情
     *
     * @return
     */
    @RequestMapping(value = "/consultLogstics", method = RequestMethod.GET)
    public JsonResp consultLogstics(Long orderId) {
        log.debug("获取订单物流详情");
        if (null == orderId)
            return JsonResp.toFail("订单id不能为空");
        Orders orders = ordersService.selectById(orderId);
        JSONObject jsonObject = new JSONObject();
        if (orders.getIsLogistics() == 0)
            return JsonResp.ok(jsonObject);
        String type = orders.getLogiCom();
        String postid = orders.getLogisticsNumber();
       /* String type="shentong";
        String postid="3333872084245";*/
        String consultUrl = "http://www.kuaidi100.com/query?type=" + type + "&postid=" + postid;
        String result = HttpClientUtil.sendGetSSLRequest(consultUrl, "UTF-8");
        Object obj = JSON.parse(result); //jsonObject会报错
        return JsonResp.ok(obj);
    }


    /**
     * 根据订单id查询订单详情
     *
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/getOrderDetailByOrderIdAdmin", method = RequestMethod.GET)
    public JsonResp getOrderDetailByOrderIdAdmin(Long orderId) {
        log.debug("根据订单id查询订单详情");
        if (null == orderId)
            return JsonResp.toFail("server:订单id不能为空");
        Orders orders = ordersService.selectById(orderId);
        orders.setLogiCom(ShippingEnum.getLogiComNameByCode(orders.getLogiCom()));
        List<OrderGoods> ogList = orderGoodsService.selectOrderGoodsByOrderId(orderId);
        orders.setOrderGoodsList(ogList);
/*        Long addressId = orders.getAddressId();
        //获取收货地址、收货人等信息
        if (null != addressId) {
            Address tempAddress = addressService.selectById(addressId);
            orders.setAddress(tempAddress);
        }*/
        //获取买家信息
        Long muserId = orders.getMuserId();
        if (null != muserId) {
            Muser tempMuser = muserService.selectById(muserId);
            orders.setMuser(tempMuser);
        }

        return JsonResp.ok(orders);
    }

    /**
     * 后台根据订单id获取订单物流详情
     *
     * @return
     */
    @RequestMapping(value = "/consultLogsticsAdmin", method = RequestMethod.GET)
    public JsonResp consultLogsticsAdmin(Long orderId) {
        log.debug("获取订单物流详情");
        if (null == orderId)
            return JsonResp.toFail("订单id不能为空");
        Orders orders = ordersService.selectById(orderId);
        JSONObject jsonObject = new JSONObject();
        if (null == orders.getIsLogistics() || orders.getIsLogistics() == 0)
            return JsonResp.ok("暂无物流信息");
        String type = orders.getLogiCom();
        String postid = orders.getLogisticsNumber();
       /* String type="shentong";
        String postid="3333872084245";*/
        String consultUrl = "http://www.kuaidi100.com/query?type=" + type + "&postid=" + postid;
        String result = HttpClientUtil.sendGetSSLRequest(consultUrl, "UTF-8");
        Object obj = JSON.parse(result); //jsonObject会报错
        return JsonResp.ok(obj);
    }


    /**
     * 计算邮费
     * 省份判断根据rongke-doc中的city.json
     *
     * @param calcuOrderRequest
     * @return
     */
/*    11.28改动 邮费设定：
1､江苏、浙江、上海  不包邮的情况下  5元。
2､四川、重庆、贵州、云南、广西、山西、陕西、海南、辽宁、黑龙江、吉林。不包邮的情况下  15元
3､甘肃、宁夏、青海、内蒙古、新疆、西藏 统一20元
4､其它 不包邮的情况下 10元（北京、天津、江西、安徽、广东、福建、山东、河北、河南、湖北、湖南）
*/
/*     11.29改动
1､88元包邮：江浙户包邮，其它地方按省列表金额进行计算并计算超重额。
2､全国包邮：不包括的地区按地方按省列表金额进行计算并计算超重额。
3､5元包邮（江浙沪）：江浙沪5元邮费，其它地方按省列表金额进行计算并计算续件额和超重额。
4､如果可以，填加一个自定义邮费*/
    @RequestMapping(value = "/calculatePostage", method = RequestMethod.POST)
    public JsonResp calculatePostage(@RequestBody CalcuOrderRequest calcuOrderRequest) {
        log.debug("计算邮费");
        Double postageResult = 0.0;
        Double totalPrice = calcuOrderRequest.getTotalPrice();
        List<CalcuGoods> calcuGoodsList = calcuOrderRequest.getCalcuGoodsList();
        if (null == calcuOrderRequest.getAddressId()) {
            return JsonResp.toFail("server:addressId不能为空");
        }

        Address address = addressService.selectById(calcuOrderRequest.getAddressId());
        String province = address.getProvince();

        Integer provinceTag;
        if (firstProvinces.contains(province)) {
            //邮费第一梯队，江浙沪
            provinceTag=1;
        } else if (secProvinces.contains(province)) {
            //邮费第二梯队
            provinceTag=2;
        } else if (thirdProvinces.contains(province)) {
            //邮费第三梯队
            provinceTag=3;

        } else if(fourthProvinces.contains(province)){
            //邮费第四梯队
            provinceTag=4;
        }else {
            return JsonResp.toFail("所在地区暂无配送");
        }

        EntityWrapper<DeliveryItem> ew;
        //判断总价达到88后包邮
        for (CalcuGoods calcuGoods : calcuGoodsList) {
            if(null==calcuGoods.getGoodsId()){
//                return JsonResp.toFail("如果不是最新版app，请务必更新app后重试");
                return JsonResp.toFail("因版本太旧，请先到【我的】-“设置更新”里更新软件后再购买。");
            }
            Goods goods=goodsService.selectById(calcuGoods.getGoodsId());
            Integer count=calcuGoods.getSkuCount();//同商品购买数量
            Integer postageType=goods.getPostage();//邮费编号
            Double overDeliveryPostage=goods.getOverDeliveryPostage();//超重超大的额外邮费

            postageResult+=count*overDeliveryPostage;//此商品下多件合计额外邮费

            //未指定邮费方案时
            if(null==postageType){
                return JsonResp.toFail("暂无该商品邮费方案");
            }

            //获取配送方案具体选项
            ew=new EntityWrapper<>();
            ew.eq("num",postageType);
            ew.eq("area_no",provinceTag);
            DeliveryItem item=deliveryItemService.selectOne(ew);

            Double firstPostage=item.getFirstPostage();//获取该地区首件邮费
            Double continuePostage=item.getContinuePostage();//获取该地区续件每件邮费

            //满88江浙沪包邮，去除首件和续件费
            if(provinceTag==1&&totalPriceOverPost(totalPrice)){
                firstPostage=0.0;
                continuePostage=0.0;
            }
            postageResult+=firstPostage+(count-1)*continuePostage;//首件邮费加续件总邮费
        }
        return JsonResp.ok(postageResult);
    }


    public boolean totalPriceOverPost(Double totalPrice) {
        if (totalPrice >= 88) {
            return true;
        } else return false;
    }

}